package cn.jee.jsp.util;

import jakarta.servlet.ServletException;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtil {
  final static String DRIVER = "org.hsqldb.jdbc.JDBCDriver";
  final static String URL = "jdbc:hsqldb:hsql://localhost/";
  final static String USER = "sa";
  final static String PASS = "";
  public static int update(String sql,Object[] args) throws ServletException {
    int row=-1;
    try{
      Class.forName(DRIVER);
      try(Connection con= DriverManager.getConnection(URL,USER,PASS);
          PreparedStatement pstmt=con.prepareStatement(sql);){
        for(int i=0;i<args.length;i++){
          pstmt.setObject(i+1,args[i]);
        }
        row= pstmt.executeUpdate();
      }
    }catch(Exception ex){
      throw new ServletException(ex);
    }
    return row;
  }
  public static List<String[]> query(String sql, Object[] args, String[] cols)throws ServletException{
    List<String[]> res=new ArrayList<>();
    try{
      Class.forName(DRIVER);
      try(Connection con= DriverManager.getConnection(URL,USER,PASS);
          PreparedStatement pstmt=con.prepareStatement(sql);){
        for(int i=0;i<args.length;i++){
          pstmt.setObject(i+1,args[i]);
        }
        try(ResultSet rs=pstmt.executeQuery();){
          while(rs.next()){
            String[] row=new String[cols.length];
            for(int i=0;i<cols.length;i++){
              row[i]=rs.getString(cols[i]);
            }
            res.add(row);
          }
        }
      }
    }catch(Exception ex){
      throw new ServletException(ex);
    }
    return res;
  }
  public static <T> List<T> queryByObj(String sql,Object[] args,RowProcessor<T> rowProcessor)throws ServletException{
    List<T> res=new ArrayList<>();
    try{
      Class.forName(DRIVER);
      try(Connection con= DriverManager.getConnection(URL,USER,PASS);
          PreparedStatement pstmt=con.prepareStatement(sql);){
        for(int i=0;i<args.length;i++){
          pstmt.setObject(i+1,args[i]);
        }
        try(ResultSet rs=pstmt.executeQuery();){
          while(rs.next()){
            T row=rowProcessor.process(rs);
            res.add(row);
          }
        }
      }
    }catch(Exception ex){
      throw new ServletException(ex);
    }
    return res;
  }
}
